package Sale;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.*;

public class SaleGoods implements Runnable {
    private static int availableGoods = 100;
    private static Lock lock = new ReentrantLock();
    private int totalGoodsToBuy;
    private boolean soldOut = false;

    public SaleGoods(int totalGoodsToBuy) {
        this.totalGoodsToBuy = totalGoodsToBuy;
    }

    @Override
    public void run() {
        while (!soldOut) {
            lock.lock();
            try {
                if (availableGoods > 0 && totalGoodsToBuy > 0) {
                    System.out.println(Thread.currentThread().getName() + " 卖出第 " + totalGoodsToBuy + " 件商品");
                    availableGoods--;
                    totalGoodsToBuy--;

                    if (totalGoodsToBuy == 0) {
                        soldOut = true;
                    }
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (soldOut) {
            System.out.println("购物车已购买完");
        }
    }
}
